import webUrl from './url.js';
import $tools from './tools.js';
import crypt from '@/common/js/crypt.js';
import store from '@/store/index.js'
var Ajax = new Object;

const ajax = (url, datas, successCallback, failCallBack, type = "POST", isToken) => {
	let that = this;
	var data = {};
	if(JSON.stringify(datas) == JSON.stringify({})){
		data['data'] = null;
	}else{
		data['data'] = datas;
	}
	let cryptmsg = crypt.EncryptKey(data.data);
	var token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
	
	if(url == '/api/user/register' || url == '/api/user/login' || url == '/api/user/forgetPwd' ||
	url == '/api/user/sendCode' || isToken == false){ 
		var headerObj = {
			"content-type": "application/json",
			"key":cryptmsg.key
		}
	}else{
		var headerObj = {
			"content-type": "application/json",
			"Authorization": token,
			"key":cryptmsg.key
		}
	}
	var oneUrl = url;
	url = webUrl.webUrl + url
	if(type == 'GET'){
		url += Ajax.paraWay(datas);
	} 
	uni.request({
		url: url,
		// data: data.data,//参数值
		data: cryptmsg.cryptdata,//参数值
		method: type || 'POST',
		dataType: 'json',
		async: false,
		sslVerify: false,
		header: headerObj,
		success: (res) => {
			var code = res.data.code; 
			var errorCode = res.data.errorCode; 
			if (code == 200) {
				successCallback(res.data);
			} else if (code == 400 || code == 401) {
				if (getApp().globalData.is_flag) {
					getApp().globalData.is_flag = false;
					console.log('token失效');
					setTimeout(() => {
						$tools.toastRedirectTo(res.data.msg, '/pages/operate/login');
						
						uni.removeStorageSync('token');
						uni.removeStorageSync('user');
					}, 100)
					
					setTimeout(() => {
						getApp().globalData.is_flag = true;
					}, 1000)
				}
			}  else {
				$tools.toast(res.data.msg);
				// console.log("failCallBack：",failCallBack);
				if(failCallBack){
					failCallBack(res.data);
				}
			} 
		},
		fail: (e) => {
			console.log(e);
			if(failCallBack){
				failCallBack();
			}
			uni.stopPullDownRefresh()
		}
	})
}

Ajax.paraWay = function(datas){
	// if(type == 'GET'){
		let url = '';
		if(datas && JSON.stringify(datas) != '{}' && datas != ''){
			// console.log(Object.keys(datas));
			// console.log(Object.values(datas));
			url += '?';
			Object.keys(datas).forEach((item,index) =>{
				url += (item+"="+Object.values(datas)[index])+'&'
			})
		}
		let can = url.slice(0, -1);
		return can;
	// }
}

export default ajax
